<?php
namespace app\admin\service;

use app\admin\exception\LogicException;
use app\admin\model\Config as Model;
use app\admin\validate\ConfigValidate as Validate;
use helper\form\Builder;

class System extends AdminService 
{

	  protected function init(){
        $this->model = new Model();
        $this->validate = new Validate();
    }

	public function getConfigHtml(){
		$group = $this->request->request('group/s','base');
		$list = $this->model->where('group',$group)->order('sort asc')->select();
		if($list->isEmpty()){
			return '';
		}

		$list = $list->toArray();
		return (new Builder($list))->getHtml();
	}

	public function create()
	{
		$group = $this->request->get('group/s','base');

		$fileFields = $this->model->where('group',$group)->where('type','in',['image','images','file','files'])->column('key');
		$data = $this->request->post();

		foreach($fileFields as $value){
			try{
				$data[$value] = \app\admin\model\FileManager::upload($this->request->file($value));
			}catch (\Exception $e){
				$data[$value] = $data[$value.'file'];
			}
            unset($data[$value.'file']);
        }
		$this->model->startTrans();
		$success = 0;
		//组装修改数据
		foreach($data as $key => $value){
			$updateModel = $this->model->where(['group'=>$group,'key'=>$key])->findOrEmpty();
			if($updateModel->isEmpty()){
				continue;
			}

			if(in_array($updateModel->type,['checkbox','files','images'])){
				$value = join(',',$value);
			}
			$updateModel->value = $value;
			if( $updateModel->save() !== false){
				++$success;
			}
		}
		if($success == count($data)){
			$this->model->commit();
			return $this->success('设置已保存');
		}
		$this->model->rollback();
		throw new LogicException('设置保存失败');
	}

}

